import { useStore } from 'vuex'
import { computed } from 'vue'
import { setStorage, getStorage } from '@/utils/storage'
export default function useFavorite() {
  const store = useStore()
  const favoriteList = computed(() => store.state.favoriteList)

  // 设置是否收藏图标
  function getFavoriteIcon(song) {
    return isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
  }

  // 收藏或者取消收藏
  function toggleFavorite(song) {
    let list = getStorage('favoriteList', 'local') || []
    if (isFavorite(song)) {
      // 取消收藏
      list.forEach((v, i) => {
        if (v.id === song.id) {
          list.splice(i, 1)
        }
      })
    } else {
      // 收藏
      list.push(song)
    }
    store.commit('setFavoriteList', list)
    setStorage('favoriteList', list, 'local')
  }

  // 判断是否收藏
  function isFavorite(song) {
    return (
      favoriteList.value.findIndex(item => {
        return item.id === song.id
      }) > -1
    )
  }
  return {
    getFavoriteIcon,
    toggleFavorite
  }
}
